package com.zty.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.zty.entity.User;
import com.zty.util.HttpUtils;
import com.zty.util.JsonHandleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author tyzhang
 * @Date: 2021/1/19 14:24
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private JsonHandleUtil jsonHandleUtil;

    @GetMapping("/login")
    public String login(String userName, String password){
        System.out.println(userName+"========================================"+password);
        if (!(StringUtils.hasLength(userName) || StringUtils.hasLength(password))) {
            return "请输入用户名和密码！";
        }
        // 用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName,password);

        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e){
            log.error("用户名不存在",e);
            return "用户名不存在";
        }catch (AuthenticationException e){
            log.error("账号或密码错误！", e);
            return "账号或密码错误！";
        }catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return "没有权限";
        }
        return "login success";
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    @RequiresPermissions("query")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequiresPermissions("add")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }

    @GetMapping("/getTest")
    public String getTest() throws JsonProcessingException {
        jsonHandleUtil.handler();
        return "add success!";
    }

    @GetMapping("/getUrl")
    public String getUrl() throws IOException {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.getStr();
        return "add success!";
    }
}
